<template>
  <div class="container">
    <!-- 帖子标题 -->
    <div class="title">
      <h1>{{ post.title }}</h1>
    </div>
    <!-- 回帖按钮 -->
    <div class="float-button-container">
      <a-float-button @click="handlePost(post.postId)" class="float-button">回帖</a-float-button>
    </div>
    <!-- 帖子列表 -->
    <div class="postList">
      <!-- 楼主帖子 -->
      <div class="post">
        <!-- 楼主信息 -->
        <div class="avater">
          <span>楼主：{{ User.username }}</span>
          <el-avatar
            shape="square"
            :size="200"
            :fit="fit"
            :src="post.postAvater"
            @click="UserPage(User.id)"
          />
          <span>id:{{ User.id }}</span>
          <span>点赞数: {{ User.support }}</span>
        </div>
        <!-- 帖子内容 -->
        <div class="postContent">
          <div class="content" v-html="post.postContent"></div>
          <div class="post-meta">
            <span>{{ post.time }}</span>
            <button
              @click="togetPostLike()"
              :class="['like-button', { liked: post.beSupport }]"
            >
              {{ post.beSupport ? "已点赞" : "点赞" }} ({{ post.support }})
            </button>
            <el-button @click="handleComment(post.postId, post.postId)">回复</el-button>
          </div>
          <span>回复</span>
          <!-- 评论列表 -->
          <div class="comments">
            <div
              v-for="(comment, commentIndex) in post.commentList ? post.commentList.slice(0, 3) : []"
              :key="commentIndex"
            >
              <div class="comment">
                <span v-if="comment.userName == User.username">楼主</span>
                {{ comment.userName }}
                <el-avatar :src="comment.avator" ></el-avatar>
                <div v-if="comment.parentName">回复{{ comment.parentName }}:</div>
                <div class="comment-content" v-html="comment.content"></div>
                <button
                  @click="toggleLike(commentIndex)"
                  :class="['like-button', { liked: comment.beSupport }]"
                >
                  {{ comment.beSupport ? "已点赞" : "点赞" }} ({{ comment.commentSupport }})
                </button>
                <el-button @click="handleComment(comment.commentId, post.postId)">回复</el-button>
                <div class="comment-time">{{ comment.commentTime }}</div>
              </div>
            </div>
          </div>
          <el-button @click="postCommnetDialog = true">全部评论</el-button>
        </div>
      </div>
      <!-- 子帖子列表 -->
      <div class="post">
        <div
          v-for="(childPost, childPostIndex) in postList"
          :key="childPostIndex"
        >
          <div class="post">
            <!-- 子帖子用户信息 -->
            <div class="avater">
              <el-avatar
                shape="square"
                :size="200"
                :fit="fit"
                :src="childPost.postAvater"
                @click="UserPage(childPost.user.id)"
              />
              <span>id:{{ childPost.user.id }}</span>
              <span>{{ childPost.user.username }}</span>
              <span>点赞数:{{ childPost.user.support }}</span>
            </div>
            <!-- 子帖子内容 -->
            <div class="postContent">
              <div class="content" v-html="childPost.postContent"></div>
              <div class="post-meta">
                <span>{{ childPost.time }}</span>
                <button
                  @click="togetChildPostLike(childPostIndex)"
                  :class="['like-button', { liked: childPost.beSupport }]"
                >
                  {{ childPost.beSupport ? "已点赞" : "点赞" }} ({{ childPost.support }})
                </button>
                <el-button @click="handleComment(childPost.postId, childPost.postId)">回复</el-button>
              </div>
              <span>回复</span>
              <!-- 子帖子评论列表 -->
              <div class="comments">
                <el-scrollbar height="200px">
                  <div
                    v-for="(comment, commentIndex) in childPost.commentList"
                    :key="commentIndex"
                  >
                    <div class="comment">
                      <span v-if="comment.userName == User.username">楼主</span>
                      {{ comment.userName }}
                      <el-avatar :src="comment.avator"></el-avatar>
                      <div v-if="comment.parentName">回复{{ comment.parentName }}:</div>
                      <div class="comment-content" v-html="comment.content"></div>
                      <button
                        @click="childtoggleLike(commentIndex, childPostIndex)"
                        :class="['like-button', { liked: comment.beSupport }]"
                      >
                        {{ comment.beSupport ? "已点赞" : "点赞" }} ({{ comment.commentSupport }})
                      </button>
                      <el-button @click="handleComment(comment.commentId, childPost.postId)">回复</el-button>
                      <div class="comment-time">{{ comment.commentTime }}</div>
                    </div>
                  </div>
                </el-scrollbar>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 全部评论对话框 -->
    <el-dialog
      v-model="postCommnetDialog"
      title="Tips"
      width="500"
      :before-close="handleClose"
    >
      <div
        v-for="(comment, commentIndex) in post.commentList"
        :key="commentIndex"
      >
        <div class="comment">
          <span v-if="comment.userName == User.username">楼主</span>
          {{ comment.userName }}
          <el-avatar :src="comment.avator"></el-avatar>
          <div v-if="comment.parentName">回复{{ comment.parentName }}:</div>
          <div class="comment-content" v-html="comment.content"></div>
          <button
            @click="toggleLike(commentIndex)"
            :class="['like-button', { liked: comment.beSupport }]"
          >
            {{ comment.beSupport ? "已点赞" : "点赞" }} ({{ comment.commentSupport }})
          </button>
          <el-button @click="handleComment(comment.commentId, post.postId)">回复</el-button>
          <div class="comment-time">{{ comment.commentTime }}</div>
        </div>
      </div>
      <button @click="postCommnetDialog = false">确定</button>
    </el-dialog>
    <!-- 回帖/回复对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="Tips"
      width="800"
      :before-close="handleClose"
    >
      <span>This is a message</span>
      <template #footer>
        <div class="editor-container">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
          />
          <Editor
            style="height: 500px; overflow-y: hidden"
            v-model="valueHtml"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="handleCreated"
          />
          <div class="button-container">
            <el-button @click="toPost()">回帖/回复</el-button>
            <el-button @click="toPostcancel()">取消</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
    <!-- 返回顶部按钮 -->
    <a-back-top />
  </div>
</template>

<script setup>
import "@wangeditor/editor/dist/css/style.css";
import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import axios from "axios";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { config, userConfig } from "@/config/config";

onMounted(() => {
  setTimeout(() => {
    valueHtml.value = "请输入内容";
  }, 1500);

  if (
    (localStorage.getItem("userId") != null) &
    (localStorage.getItem("token") != null)
  ) {
    console.log("登陆了");
    getpost();
    getpostList();
  } else {
    console.log("没登陆");
    userGetpost();
    userGetpostList();
  }
});

onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

let post = ref({});
const router = useRoute();
const route= useRouter();
let User = ref({});
let postId = ref({});
let postMasterId = router.query.post;
let isLiked = ref(false);
const dialogVisible = ref(false);
const postOrComment = ref(false);
let commentforPost = ref();
let postList = ref();
const postCommnetDialog = ref(false);
const backPostComment = ref(false);
let currentChange = ref(1);

// let config = {
//   headers: {
//     token: localStorage.getItem("token"),
//   },
// };
// let userConfig = {
//   headers: {
//     token: "token",
//   },
// };
let supoort = ref({
  supportId: "",
  postId: "",
  userId: "",
  time: "",
});
let toback = ref();

const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref("<p>hello</p>");
const toolbarConfig = {};
const editorConfig = { 
  placeholder: "请输入内容...",
MENU_CONF: {
    
  }
 };
 editorConfig.MENU_CONF['uploadImage'] = {
    async customUpload(file, insertFn) {                   // JS 语法
    // file 即选中的文件
    // 自己实现上传，并得到图片 url alt href
    // 最后插入图片
   const finalurl= await handleFileChange(file)
   console.log("response:"+finalurl)
    insertFn(finalurl, null, finalurl)
  }
  }

const getpost = async () => {
  await axios
    .get("api/posts/getPost/" + router.query.post, config)
    .then(function (response) {
      post.value = response.data.data;
      console.log(post);
      let userid = {
        id: post.value.postMaster,
      };

      console.log(userid);
      axios
        .post("api/user/getUser", userid, userConfig)
        .then(function (response) {
          User.value = response.data.data;
          console.log(User.value);
          console.log(User.value);
        });
    });
};

const userGetpost = async () => {
  await axios
    .get("api/posts/getPost/" + router.query.post, userConfig)
    .then(function (response) {
      post.value = response.data.data;
      console.log(post);
      let userid = {
        id: post.value.postMaster,
      };

      console.log(userid);
      axios
        .post("api/user/getUser", userid, userConfig)
        .then(function (response) {
          User.value = response.data.data;
          console.log(User);
          User.id = "1";
          console.log(User.id);
        });
    });
};

const getpostList = async () => {
  console.log("请求帖子" + router.query.post + "的回帖列表");
  postList.value = await axios
    .get("api/posts/backPostList/" + router.query.post, config)
    .then(function (response) {
      postList = response.data.data;
      console.log("回帖列表" + postList[0]);
    });
};
const userGetpostList = async () => {
  console.log("请求帖子" + router.query.post + "的回帖列表");
  if (localStorage.getItem("token") == null) {
    postList.value = await axios
      .get("api/posts/backPostList/" + router.query.post, userConfig)
      .then(function (response) {
        postList = response.data.data;
        console.log("回帖列表" + postList[0]);
      });
  } else {
    postList.value = await axios
      .get("api/posts/backPostList/" + router.query.post, config)
      .then(function (response) {
        postList = response.data.data;
        console.log("回帖列表" + postList[0]);
      });
  }
};

function childtoggleLike(commentIndex, childPostIndex) {
  if (localStorage.getItem("userId") == null) {
    alert("请先登录");
  } else {
    console.log(postList[childPostIndex].commentList[commentIndex].beSupport);
    if (postList[childPostIndex].commentList[commentIndex].beSupport) {
      supoort.value.postId =
        postList[childPostIndex].commentList[commentIndex].commentId;
      supoort.value.userId = localStorage.getItem("userId");
      axios.post("api/posts/delSupport", supoort.value, config);
      postList[childPostIndex].commentList[commentIndex].commentSupport -= 1;
      console.log(
        postList[childPostIndex].commentList[commentIndex].commentSupport
      );
      alert("已取消点赞");
    } else {
      supoort.value.postId =
        postList[childPostIndex].commentList[commentIndex].commentId;
      supoort.value.userId = localStorage.getItem("userId");
      axios.post("api/posts/support", supoort.value, config);
      postList[childPostIndex].commentList[commentIndex].commentSupport += 1;
      console.log(
        postList[childPostIndex].commentList[commentIndex].commentSupport
      );
      alert("点赞成功");
    }
    postList[childPostIndex].commentList[commentIndex].beSupport =
      !postList[childPostIndex].commentList[commentIndex].beSupport;

    console.log(postList[childPostIndex].commentList[commentIndex].beSupport);
  }
}

// function toggleLike(commentIndex) {
//   if (localStorage.getItem("userId") == null) {
//     alert("请先登录");
//   } else {
//     if (post.value.commentList[commentIndex].beSupport == false) {
//       supoort.value.postId = post.value.commentList[commentIndex].commentId;
//       supoort.value.userId = localStorage.getItem("userId");
//       axios.post("api/posts/support", supoort.value,config);
//       post.value.commentList[commentIndex].commentSupport += 1;
//     } else {
//       supoort.value.postId = post.value.commentList[commentIndex].commentId;
//       supoort.value.userId = localStorage.getItem("userId");
//       axios.post("api/posts/delSupport", supoort.value,config);
//       post.value.commentList[commentIndex].commentSupport -= 1;
//     }
//     post.value.commentList[commentIndex].beSupport =
//       !post.value.commentList[commentIndex].beSupport;
//   }
// }
function toggleLike(commentIndex) {
  if (localStorage.getItem("userId") == null) {
    alert("请先登录");
  } else {
    if (post.value.commentList[commentIndex].beSupport == false) {
      supoort.value.postId = post.value.commentList[commentIndex].commentId;
      supoort.value.userId = localStorage.getItem("userId");
      axios.post("api/posts/support", supoort.value, config);
      post.value.commentList[commentIndex].commentSupport += 1;
    } else {
      supoort.value.postId = post.value.commentList[commentIndex].commentId;
      supoort.value.userId = localStorage.getItem("userId");
      axios.post("api/posts/delSupport", supoort.value, config);
      post.value.commentList[commentIndex].commentSupport -= 1;
    }
    post.value.commentList[commentIndex].beSupport =
      !post.value.commentList[commentIndex].beSupport;
  }
}
function togetPostLike() {
  if (localStorage.getItem("userId") == null) {
    alert("请先登录");
  } else {
    if (post.value.beSupport == false) {
      supoort.value.postId = post.value.postId;
      supoort.value.userId = localStorage.getItem("userId");
      axios.post("api/posts/support", supoort.value, config);
      post.value.support += 1;
    } else {
      supoort.value.postId = post.value.postId;
      supoort.value.userId = localStorage.getItem("userId");
      axios.post("api/posts/delSupport", supoort.value, config);
      post.value.support -= 1;
    }
    post.value.beSupport = !post.value.beSupport;
  }
}

function togetChildPostLike(childPostIndex) {
  if (localStorage.getItem("userId") == null) {
    alert("请先登录");
  } else {
    if (postList[childPostIndex].beSupport == false) {
      supoort.value.postId = postList[childPostIndex].postId;
      supoort.value.userId = localStorage.getItem("userId");
      axios.post("api/posts/support", supoort.value, config);
      postList[childPostIndex].support += 1;
      alert("点赞成功");
    } else {
      supoort.value.postId = postList[childPostIndex].postId;
      supoort.value.userId = localStorage.getItem("userId");
      axios.post("api/posts/delSupport", supoort.value, config);
      postList[childPostIndex].support -= 1;
      alert("取消点赞");
    }
    postList[childPostIndex].beSupport != postList[childPostIndex].beSupport;
  }
}

const toPostcancel = () => {
  dialogVisible.value = false;
  valueHtml.value = "<p></p>";
};
function toPost(Id) {
  console.log(valueHtml.value);
  dialogVisible.value = false;
  console.log(Id);
  if (postOrComment.value == true) {
    axios
      .post(
        "api/posts/comment",
        {
          commentId: "",
          userName: localStorage.getItem("userId"),
          parentId: toback.value,
          content: valueHtml.value,
          commentTime: "",
          support: 0,
          avator: "",
          postId: backId.value,
          beSupport: "false",
          parentName: "",
        },
        config
      )
      .then(function (response) {
        if (response.data.code != 200) {
          alert("操作失败");
        }
      });
  } else {
    axios.post(
      "api/posts/backPost",
      {
        postId: "",
        title: "",
        postMaster: localStorage.getItem("userId"),
        time: "",
        support: "0",
        comments: "0",
        forward: "0",
        sectionId: "",
        isBan: "0",
        postContent: valueHtml.value,
        beSupport: "",
        commentList: [],
        postAvater: "",
        parentPostId: toback.value,
      },
      config
    );
  }
  location.reload();
}

function handlePost(Id) {
  if (localStorage.getItem("userId") == null) {
    alert("请先登录");
  } else {
    postOrComment.value = false;
    dialogVisible.value = true;
    toback.value = Id;
    console.log(postOrComment.value);
  }
}
let backId = ref("");
function handleComment(Id, postId) {
  if (localStorage.getItem("userId") == null) {
    alert("请先登录");
  } else {
    postOrComment.value = true;
    backId.value = postId;
    console.log(backId.value);
    dialogVisible.value = true;
    toback.value = Id;
  }
}

function handlepostCommnetDialog() {
  postCommnetDialog = true;
}

function UserPage(userid){
  console.log(userid)
  route.push({
    name:"UserPage",
    query:{
      user:userid
    }
  })
}

const handleFileChange = async (Image) => {
    const file = Image
    console.log("选择文件已触发")
    if (file) {
      console.log("已找到文件")
      const qiniuKey = await uploadAvatarToQiniu(file);
      if (qiniuKey) {
        console.log("开始上传")
        const domain = 'http://svftekle7.hn-bkt.clouddn.com'; // 替换为你的七牛云存储空间域名
        const avatarUrl = `${qiniuKey}`;
        const finalUrl = domain+"/"+avatarUrl;
        return finalUrl
        //await sendAvatarUrlToBackend(avatarUrl);
      }
    }
  };

  // 从后端获取上传凭证的函数，这里假设你有一个后端接口可以返回 token
const getUploadToken = async () => {
  const userDto={
    id:''
  }
  try {
    const response = await axios.post('api/user/getQiniuToken',userDto,config)
    console.log(response)
    return response.data.data
    
  } catch (error) {
    console.error('获取上传凭证失败:', error);
    return null;
  }
};
let QiniuToken=ref()
// 上传头像到七牛云的函数
const uploadAvatarToQiniu = async (file) => {
  const token = await getUploadToken();
  QiniuToken.value=token;
  if (!token) {
    console.log("没有token",token)
    return;
  }

  const formData = new FormData();
  formData.append('token', token);
  formData.append('file', file);

  try {
    const response = await axios.post('https://up-z2.qiniup.com', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    console.log('上传到七牛云成功:', response.data);
    //const finalUrl = domain+"/"+url;
    return response.data.key;
  } catch (error) {
    console.error('上传到七牛云失败:', error);
    return null;
  }
};
</script>

<style scoped>
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f5f8ff;
}

.title {
  text-align: center;
  color: #ff69b4;
  margin-bottom: 20px;
}

.float-button-container {
  position: fixed;
  bottom: 20px;
  right: 20px;
}

.float-button {
  background-color: #00bfff;
  color: white;
  border: none;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  font-size: 16px;
  cursor: pointer;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  transition: background-color 0.3s ease;
}

.float-button:hover {
  background-color: #009acd;
}

.post {
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.avater {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.avater span {
  margin-right: 10px;
}

.postContent {
  margin-top: 10px;
}

.content {
  max-width: 800px;
  padding: 10px;
  line-height: 1.6;
}

.post-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
  color: #888;
}

.like-button {
  background-color: #eee;
  border: none;
  border-radius: 5px;
  padding: 5px 10px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.like-button.liked {
  background-color: #ff69b4;
  color: white;
}

.like-button:hover {
  background-color: #ddd;
}

.comments {
  margin-top: 10px;
}

.comment {
  border-top: 1px solid #eee;
  padding: 10px 0;
}

.comment-content {
  margin: 5px 0;
}

.comment-time {
  font-size: 12px;
  color: #888;
}

.editor-container {
  border: 1px solid #ccc;
  padding: 20px;
}

.button-container {
  margin-top: 20px;
  text-align: right;
}
</style>